import axios from 'axios'
import {BASE_URL} from '../util/name'
 
axios.defaults.timeout = 5000 // 超时时间设置
axios.defaults.baseURL = BASE_URL
// Content-Type 响应头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
 
// response 拦截器
// 可以在接口响应后统一处理结果
axios.interceptors.response.use(
    response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        return res;
    }
    ,
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)
 
 
/**
   * 封装get方法
   * @param url
   * @param data
   * @returns {Promise}
   */
 export function get (url, params = {}, responseType = 'json') {
    return new Promise((resolve, reject) => {
      axios.get(url, {
        params: params,
        responseType
      })
        .then(response => {
          resolve(response.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
  
  /**
     * 封装post请求
     * @param url
     * @param data
     * @returns {Promise}
     */
  export function post (url, data = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, data)
        .then(response => {
          resolve(response.data)
        }, err => {
          reject(err)
        })
    })
  }
  
  /**
     * 封装delete请求
     * @param url
     * @param data
     * @returns {Promise}
     */
  export function deletes (url, data = {}) {
    return new Promise((resolve, reject) => {
      axios.delete(url, data)
        .then(response => {
          resolve(response.data)
        }, err => {
          reject(err)
        })
    })
  }
 